/**
 * Windows原生部署管理器
 * 使用PowerShell和Windows OpenSSH实现文件传输
 * @author lihengtt <lihengsir@gmail.com>
 * @github https://github.com/lihengtt
 */
import * as vscode from 'vscode';
import { exec } from 'child_process';
import { ServerInfo } from './types';

export class WindowsDeployManager {
    /**
     * 测试连接到远程服务器
     */
    async testConnection(serverInfo: ServerInfo): Promise<boolean> {
        const testCommand = `ssh -p ${serverInfo.port} -o ConnectTimeout=10 -o BatchMode=yes ${serverInfo.username}@${serverInfo.host} "echo 'Connection test successful'"`;
        
        return new Promise((resolve) => {
            exec(testCommand, (error, _stdout, _stderr) => {
                if (error) {
                    vscode.window.showErrorMessage(`连接测试失败: ${error.message}`);
                    resolve(false);
                } else {
                    vscode.window.showInformationMessage('连接测试成功');
                    resolve(true);
                }
            });
        });
    }
    
    /**
     * 使用SCP上传文件（Windows 10+ 内置OpenSSH）
     */
    async uploadFile(localPath: string, serverInfo: ServerInfo, remotePath: string): Promise<boolean> {
        const scpCommand = `scp -P ${serverInfo.port} "${localPath}" ${serverInfo.username}@${serverInfo.host}:"${remotePath}"`;
        
        return new Promise((resolve) => {
            exec(scpCommand, (error, _stdout, _stderr) => {
                if (error) {
                    vscode.window.showErrorMessage(`上传失败: ${error.message}`);
                    resolve(false);
                } else {
                    vscode.window.showInformationMessage('文件上传成功');
                    resolve(true);
                }
            });
        });
    }
    
    /**
     * 使用SCP下载文件
     */
    async downloadFile(remotePath: string, serverInfo: ServerInfo, localPath: string): Promise<boolean> {
        const scpCommand = `scp -P ${serverInfo.port} ${serverInfo.username}@${serverInfo.host}:"${remotePath}" "${localPath}"`;
        
        return new Promise((resolve) => {
            exec(scpCommand, (error, _stdout, _stderr) => {
                if (error) {
                    vscode.window.showErrorMessage(`下载失败: ${error.message}`);
                    resolve(false);
                } else {
                    vscode.window.showInformationMessage('文件下载成功');
                    resolve(true);
                }
            });
        });
    }
    
    /**
     * 同步整个目录
     */
    async syncDirectory(_localDir: string, _serverInfo: ServerInfo, _remoteDir: string): Promise<boolean> {
        // Windows可以使用robocopy + SSH的组合，或者逐个文件上传
        vscode.window.showWarningMessage('Windows系统建议使用SFTP方式进行目录同步');
        return false;
    }
}